package config

import (
	"example.com/myproject/project/global"
	"example.com/myproject/project/utils"
	"fmt"
	"github.com/olahol/melody"
	"log"
	"sync"
)

var (
	userSessions = make(map[string]*melody.Session) //map<string,session> name和session
	mu           sync.RWMutex
)

var Melody *melody.Melody

func initMelody() {
	Melody = melody.New()
	Melody.HandleConnect(func(s *melody.Session) {
		fmt.Println("WebSocket connected")
		token := s.Request.Header.Get("token")
		userID, _ := utils.ParseJWT(token) //项目里的函数
		if userID == "" {
			log.Println("No user ID provided, closing connection")
			s.Close()
			return
		}

		s.Set("user_id", userID)
		// 将用户 ID 与 Session 关联起来
		mu.Lock()
		userSessions[userID] = s
		mu.Unlock()
		fmt.Println("User connected:", userID)
	})
	//todo
	Melody.HandleMessage(func(s *melody.Session, msg []byte) {
		fmt.Println("Received message:", string(msg))
		msgType := global.MSGid(msg[0])
		switch msgType {
		case global.MSG_BROAD:
			Melody.Broadcast(msg[1:]) //melody可以广播，也可以用我们保存的map广播
		case global.MSG_SEND:
			//melody并没有直接提供“按用户发送消息”的功能，需要用我们保存的map
			toUserID := string(msg[1:2])
			content := msg[2:]
			mu.RLock()
			session, exists := userSessions[toUserID]
			mu.RUnlock()
			if !exists {
				fmt.Println("user not found")
				return
			}
			session.Write(content)
		default:
			fmt.Println("default")
		}
		Melody.Broadcast(msg)
	})

	Melody.HandleDisconnect(func(s *melody.Session) {
		log.Println("Client disconnected:", s.RemoteAddr())

		userID, exists := s.Get("user_id")
		if !exists {
			return
		}

		mu.Lock()
		delete(userSessions, userID.(string))
		mu.Unlock()

		log.Println("User disconnected:", userID)
	})

}
